package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.WechatMiniProgramProperties;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sjqn
 */
@Service
@Slf4j
public class WechatServiceImpl implements WechatService {


    // 登录
    private static final String REQUEST_URL =
            "https://api.weixin.qq.com/sns/jscode2session?" +
                    "grant_type=authorization_code";

    // 获取token
    private static final String ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL =
            "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Autowired
    private WechatMiniProgramProperties wechatMiniProgramProperties;

    /**
     * 获取openid
     *
     * @param code 登录凭证
     * @return
     */
    @Override
    public String getOpenid(String code) {

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", wechatMiniProgramProperties.getAppid());
        requestUrlParam.put("secret", wechatMiniProgramProperties.getAppSecret());
        requestUrlParam.put("js_code", code);
        requestUrlParam.put("grant_type", "authorization_code");

        String result = HttpUtil.get(REQUEST_URL, requestUrlParam);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 若code不正确【即errcode存在】，则获取不到openid，响应失败
        Integer errcode = jsonObject.getInt("errcode");
        if (ObjectUtil.isNotEmpty(errcode)) {
            log.error("获取openid失败，错误码：{}，错误信息：{}", errcode, jsonObject.getStr("errmsg"));
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");

    }

    /**
     * 获取手机号
     *
     * @param code 手机号凭证
     * @return
     */
    @Override
    public String getPhone(String code) {

        //获取access_token
        String token = getAccessToken();
        //拼接请求路径
        String url = PHONE_REQUEST_URL + token;

        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(param));

        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            log.error("获取手机号失败，错误码：{}，错误信息：{}",
                    jsonObject.getInt("errcode"),
                    jsonObject.getStr("errmsg"));
            //若code不正确，则获取不到phone，响应失败
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");

    }

    public String getAccessToken() {

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", wechatMiniProgramProperties.getAppid());
        requestUrlParam.put("secret", wechatMiniProgramProperties.getAppSecret());
//        requestUrlParam.put("js_code", "client_credential");
        requestUrlParam.put("grant_type", "authorization_code");

        String result = HttpUtil.get(ACCESS_TOKEN_URL, requestUrlParam);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        //如果code不正确，则失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}